package com.ruanko.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 显示所有down目录的文件,供下载所用
 */
@SuppressWarnings("serial")
public class DownloadListAction  extends ActionSupport{
    
    private  ArrayList<String> filelist = new ArrayList<String>();
    
    
    /**
     *    可以是前台一个页面传入,也可以是手动指定,其作用是指定下载文件的根目录
     */
    private String downloadRootPath = "/files/";
    
	public String getDownloadRootPath() {
        return downloadRootPath;
    }
    public void setDownloadRootPath(String downloadRootPath) {
        this.downloadRootPath = downloadRootPath;
    }


    /**
     * 将指定文件路径下的文件全部遍历出来 
     */
    public  void refreshFileList(String strPath)
    {
        File dir = new File(strPath);
        if (dir.exists() == false) {
       	   dir.mkdirs();
       	  }
        File[] files = dir.listFiles();

        if (files == null)
            return;
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].isDirectory())
            {
                refreshFileList(files[i].getAbsolutePath());
            } else
            {
                String filePath =  files[i].getPath();
                filelist.add(filePath);
            }
        }
    }

    
    
    /**
     * 格式化输出数据存入Map,形式文件名+文件服务端路径
     * @param filelist 遍历出来的文件路径
     * @param downloadRootPath 指明服务器下载的文件,便于从遍历出来的文件中取得服务端路径
     */
    private  Map<String,String> formatFileMap(ArrayList<String> filelist,String downloadRootPath){
        Map<String,String> formatFileMap = new HashMap<String,String>();
        //得到服务下载的根路径,并将/换成\\,这样便于替换
        String formatDownloadRootPath =  downloadRootPath.replaceAll("/", "\\\\");
        for(String filePath : filelist){
            //得到下载的相对路径
            String  downloadPath = filePath.substring(filePath.indexOf(formatDownloadRootPath));
            System.err.println("lynn lynn "+formatDownloadRootPath);
            System.err.println("lynn lynn "+downloadPath);
            //将得到的相对路径的\\转换成/
            String formatDownloadPath = downloadPath.replaceAll("\\\\", "/");
            //得到文件名
            String filename = formatDownloadPath.substring(formatDownloadPath.lastIndexOf("/")+1);
        
            /*try {
                formatFileMap.put(filename, URLEncoder.encode(formatDownloadPath, "gbk"));
            } catch (UnsupportedEncodingException e) {
                formatFileMap.put(filename, formatDownloadPath);
                e.printStackTrace();
            }*/
            
            //这就不用考虑设置编码了，再后面统一使用javascript的encodeURI函数
            formatFileMap.put(filename, formatDownloadPath);
            
        }
        return formatFileMap;
    }
    
    
    @SuppressWarnings("unchecked")
    @Override
    public String execute() throws Exception {
    	HttpSession session = ServletActionContext.getRequest().getSession(true);
		String userid = session.getAttribute("userid").toString();
		downloadRootPath += userid+"/";
        //指定下载目录
        String upload = ServletActionContext.getServletContext().getRealPath(downloadRootPath);
        System.out.println("upload::"+upload);
        //清理filelist
        filelist.clear();
        //遍历文件
        refreshFileList(upload);
        
        ActionContext context = ActionContext.getContext();
        Map request = (Map) context.get("request");
        
        
        if(filelist != null){
            //格式化文件信息,包括文件名和地址
            Map<String,String> formatFileMap = formatFileMap(filelist,downloadRootPath);
            request.put("fileMap", formatFileMap);
            upload = upload.replaceAll("\\\\", "/");
            String[] temp = upload.split("/");
            String fRootPath = "http://localhost:8080/"+temp[temp.length-3]+"/"+temp[temp.length-2]+"/"+temp[temp.length-1]+"/";
            System.err.println("fRootPath::"+fRootPath);
            request.put("fRootPath", fRootPath);
            return SUCCESS;
        }
        else{
            request.put("errorMessage", "没有相关的下载文件");
            return ERROR;
        }
            
    }
    
    
}